package com.sl.diary.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import com.sl.diary.R;
import com.sl.diary.callback.AlertDialogCallBack;
import com.sl.diary.db.AddFakeData;
import com.sl.diary.db.DBManager;
import com.sl.diary.model.TravelModel;

public class BaseActivity extends Activity {

	protected DBManager dbManager;
	protected LinearLayout navigation_bar;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.opendb();
	}

	@Override
	protected void onResume() {
		super.onResume();
		this.opendb();
	}

	@Override
	public void onPause() {
		this.closedb();
		super.onPause();
	}

	/*
	 * init common navigation bar for all activity
	 */
	protected void initNavigationBar() {
		navigation_bar = (LinearLayout) findViewById(R.id.navigationbar);
		// buttons in navigation
		ImageButton imgbtn_back = (ImageButton) findViewById(R.id.imgbtn_navigation_back);
		imgbtn_back.setOnClickListener(onClickBack);
	}

	/*
	 * handle open/close database
	 */
	protected void opendb() {
		if (dbManager == null) {
			dbManager = new DBManager(BaseActivity.this);
			dbManager.open();
			if (dbManager.getAllTravel().size() == 0) {
				AddFakeData.addTourFake(dbManager);
			}

		}
	}

	protected void closedb() {
		dbManager.close();
	}

	/**
	 * handler show alert to confirm delete travel - called at sub-activity
	 * which inherited {@link BaseActivity}
	 * 
	 * @param context
	 *            - the {@link Context}
	 * @param travel
	 *            - the {@link TravelModel}
	 */
	protected void showDeleteTravelAlert(Context context,
			final TravelModel travel, final AlertDialogCallBack callBack) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage(R.string.message_delete_travel);
		builder.setPositiveButton(R.string.message_yes,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						callBack.onAlertOKCallBack();
						dialog.dismiss();
					}
				});

		builder.setNegativeButton(R.string.message_no,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});

		AlertDialog alert = builder.create();
		alert.show();

	}

	/*
	 * implement click event of back button on navigation bar
	 */
	OnClickListener onClickBack = new OnClickListener() {

		@Override
		public void onClick(View v) {
			//onBackPressed();
			finish();
		}
	};
}
